package part18;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wcj
 * @Date 2021/6/4 19:22
 * @Version 1.0
 */
public class Part1835 {

    /**
     * 同一个流中的序列化，即便包含引用，我们反序列化也可以得到完整的对象网
     * 但是不同的名，即便是同一个对象，构造的可能也不是同一张对象网
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        House house = new House();
        ArrayList<Animal> animals = new ArrayList<>();
        animals.add(new Animal("cat", house));
        animals.add(new Animal("dog", house));
        animals.add(new Animal("bird", house));

        ByteArrayOutputStream buf1 = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(buf1);
        out.writeObject(animals);
        out.writeObject(animals);

        ByteArrayOutputStream buf2 = new ByteArrayOutputStream();
        ObjectOutputStream out2 = new ObjectOutputStream(buf2);
        out2.writeObject(animals);

        ObjectInputStream in1 = new ObjectInputStream(new ByteArrayInputStream(buf1.toByteArray()));
        ObjectInputStream in2 = new ObjectInputStream(new ByteArrayInputStream(buf2.toByteArray()));
        List animals1 = (List) in1.readObject();
        List animals2 = (List) in1.readObject();
        List animals3 = (List) in2.readObject();
        System.out.println(animals1);
        System.out.println(animals2);
        System.out.println(animals3);
    }

}

class House implements Serializable {
}

class Animal implements Serializable {
    private String name;
    private House preHouse;

    Animal(String name, House house) {
        this.name = name;
        this.preHouse = house;
    }

    @Override
    public String toString() {
        return name + "[" + super.toString() + "]" + preHouse;
    }
}
